import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by kroc on 2016/1/04.
 */
public class Download {
    public void download(String url,String filename,String savePath)throws IOException{
        InputStream inputStream=null;
        FileOutputStream fos=null;
        try {
            URL Url = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) Url.openConnection();
            //httpURLConnection.setConnectTimeout(10000);
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36");
            inputStream = httpURLConnection.getInputStream();
            byte[] getData = readInputStream(inputStream);
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + filename);
            fos = new FileOutputStream(file);
            fos.write(getData);
            getData=null;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public String getURL(String url)throws IOException{
        Document doc= Jsoup.connect(url).get();
        Elements links=doc.select("a[href]");
        Pattern p=Pattern.compile("(视频下载.*)");
        String URL=null;
        for(Element src:links){
            Matcher m=p.matcher(src.text());
            if(m.find()){
                URL=src.attr("abs:href");
                break;
            }
        }
        return URL;
    }
    private byte[]readInputStream(InputStream inputStream)throws IOException{
        byte[]buffer=new byte[1024*1024*4];
        int len=0;
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        while((len=inputStream.read(buffer))!=-1)
        {
            bos.write(buffer,0,len);
        }
        bos.close();
        return bos.toByteArray();
    }
}
